<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Http\Requests\V1\NewStudentRequest;
use App\Models\V1\ApplyPays;
use App\Models\V1\Custodians;
use App\Models\V1\NewArrival;
use App\Models\V1\NewStudent;
use App\Models\V1\ReceiveStatus;
use App\Models\V1\ResultClasses;
use App\Models\V1\ResultDorms;
use App\Models\V1\ResultMajors;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use Log;
class NewStudentsController extends Controller
{

    protected $is_first = false;

    /**
     * 显示班级数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
//        $codes = $this->getEnrollmentCodes();
//        $arrival_code = $this->getArrivalCodes();
//        $data['codes'] = $codes;
//        $data['arrival_code'] = $arrival_code;
        
        $arrival_code = $this->getArrivalCodes();
        $YearsNow = !empty(NewArrival::where('code', $arrival_code)->first()) ? NewArrival::where('code', $arrival_code)->first()->enrollment_year : '';
        $serialNow = !empty(NewArrival::where('code', $arrival_code)->first()) ? NewArrival::where('code', $arrival_code)->first()->enrollment_serial : '';
        $years = $this->getYearOrder();
        $serial = $this->getSerial();
        $data['years'] = $years;
        $data['serial'] = $serial;
        $data['YearsNow'] = $YearsNow;
        $data['SerialNow'] = $serialNow;
        return view('v1.newData.new_student',$data);
    }

    /**
     * 获取迎新换届数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];
        // 获取符合查询条件的班级数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');
        $enrollment_year = $request->get('enrollment_year');
        $enrollment_serial = $request->get('enrollment_serial');
        $arrival_code = NewArrival::where('enrollment_year', $enrollment_year)
                ->where('enrollment_serial', $enrollment_serial)
                ->first()->code;
//        if ($this->is_first == false && empty($arrival_code)) {
//            $this->is_first = true;
//            $arrival_code = $this->getArrivalCodes();
//        }
        
        // 获取符合查询条件的班级数据
        $data = $this->getNewStudentList($currentPage, $rows, $arrival_code, $keywords);
        if (!$data->isEmpty()) {
            $formatList = array();
            $count = $data->total() > 0 ? $data->total() : 0;
            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $arrival_code = $item['arrival_code'];
                    $arrivalInfo = NewArrival::where('code', $arrival_code)->first();
                    $formatItem['enrollment_year'] = $arrivalInfo->enrollment_year;
                    $formatItem['enrollment_serial'] = $arrivalInfo->enrollment_serial;
                    $exam_code = $item['exam_code'];
                    $formatItem['exam_code'] = $exam_code;
                    $formatItem['enrollment_numbering'] = $item['enrollment_numbering'];
                    $formatItem['name'] = $item['name'];
                    $formatItem['sex'] = $this->formatSexData($item['sex']);
                    $formatItem['card_type'] = $item['card_type'];
                    $formatItem['card_number'] = $item['card_number'];
                    $formatItem['major_directory_code'] = $item['major_directory_code'];
                    $formatItem['original_type'] = $item['original_type'];
                    $formatItem['admission_property'] = $item['admission_property'];
                    $formatItem['exam_province'] = $item['exam_province'];
                    $formatItem['exam_area'] = $item['exam_area'];
                    $formatItem['graduated_school'] = $item['graduated_school'];
                    $formatItem['support_type'] = $item['support_type'];
                    $formatItem['school_mode'] = $item['school_mode'];
                    $formatItem['is_dorm'] = $this->getIsDorm($exam_code);
                    $formatItem['is_pay'] = $this->getIsPay($exam_code);
                    $formatItem['is_report'] = $this->getIsRegister($exam_code);
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }
                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }
        return $response;
    }

    /**
     * 进入单条班级数据显示界面（适用于新增addData、编辑editData、查看viewData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        $data['exam_code'] = $request->input('code');
        switch ($request->input('view')) {
            case 'addData':
                return view('v1.form.new_student_item', $data);
                break;
            case 'viewData':
                $exam_code = $data['exam_code'];
                $currentStudent = $this->getNewStudentByCode($exam_code);
                $currentStudent['sex'] = $this->formatSexData($currentStudent['sex']);
                $currentStudent['is_dorm'] = $this->getIsDorm($exam_code);
                $currentStudent['is_pay'] = $this->getIsPay($exam_code);
                $currentStudent['is_report'] = $this->getIsRegister($exam_code);
                $currentStudent['admission_major'] = $this->getAdmissionMajor($exam_code);
//                2.生活用品发放 3.教材发放 4.校服发放 5.宿舍钥匙发放
                $currentStudent['is_daily_use'] = $this->getIsReceive($exam_code,2);
                $currentStudent['is_textbook'] = $this->getIsReceive($exam_code,3);
                $currentStudent['is_cloth'] = $this->getIsReceive($exam_code,4);
                $currentStudent['is_key'] = $this->getIsReceive($exam_code,5);

                $history = $currentStudent['medical_history'];

                if (empty($history) || !isset($history)) {
                    $history='';
                }else{
                    $historyArr = explode('--',$history);
                    if (count($historyArr) == 2){
                        if (!empty($historyArr[0])) {
                            $history = $historyArr[0].','.$historyArr[1];
                        }else{
                            $history = $historyArr[1];
                        }
                    }elseif (count($historyArr) == 1) {
                        $history = $historyArr[0];
                    }else {
                        $history = '';
                    }
                }
                $currentStudent['medical_history'] = $history;

                //学生班级
                $currentStudent['class_name'] = $this->getStudentClass($exam_code);

                //学生宿舍
                $currentStudent['dorm_name'] = $this->getStudentDorm($exam_code);

                //监护人
                $currentStudent['custodian'] = $this->getNewStudentCustodianByCode($exam_code);

                $data['itemData'] = $currentStudent;
                return view('v1.form.new_student_item', $data);
                break;
        }
    }
    /**
     * 显示新生信息数据导入页面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function importView(Request $request)
    {
        // 获取登录用户
        $loginUser = Auth::user();

        $data['view'] = $request->input('view');
        $data['code'] = $loginUser->getAttribute('code');

        return view('v1.form.upload_excel', $data);
    }


    /**
     * 新增基本信息
     *bail关键字表示只要第一个验证失败后面就不验了，提高效率
     * @param Request $request
     * @return array
     */
    public function addData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '新生信息[' . $request->input('exam_code') . '],新增失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $rules['enrollment_numbering'] = 'bail|required';
            $rules['exam_code'] = 'bail|required';
            $rules['name'] = 'bail|required';
            $rules['card_type'] = 'bail|required';
            $rules['card_number'] = 'bail|required';
            $rules['enrollment_directory'] = 'bail|required';
            $rules['major_directory_code'] = 'bail|required';
            $rules['captcha'] = 'bail|required|captcha';
            $messages['enrollment_numbering.required'] = '招生编号不能为空';
            $messages['exam_code.required'] = '考试号不能为空';
            $messages['name.required'] = '姓名不能为空';
            $messages['card_type.required'] = '证件类型不能为空';
            $messages['card_number.required'] = '证件号不能为空';
            $messages['enrollment_directory.required'] = '招生目录不能为空';
            $messages['major_directory_code.required'] = '专业目录代码不能为空';
            $messages['captcha.captcha'] = '验证码错误';
            $this->validate($request, $rules, $messages);

            // 新增信息
            $successFlag = $this->handleAdd($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '新生信息[' . $request->input('exam_code') . '],新增成功！';
            }
        }

        return $response;
    }
    
    /**
     * 编辑新生信息
     */
    public function updateData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '新生代码[' . $request->input('edit_exam_code') . '],更新失败！',
        ];
        
        if ($request->method() === 'POST') {
            
            // 启动学期信息
            $successFlag = $this->handleUpdateData($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '新生代码[' . $request->input('edit_exam_code') . '],更新成功！';
            }
        }
        
        return $response;
    }
    
    /**
     * 执行编辑更新新生信息
     */
    public function handleUpdateData($request){
        
        $exam_code = $request->input('edit_exam_code');
        $name = $request->input('edit_name');
        $sex = $request->input('edit_sex') == '男' ? 1 : 2;
        $mobile = $request->input('edit_mobile');
        $address = $request->input('edit_address');
        $card_type = $request->input('edit_card_type');
        $card_number = $request->input('edit_card_number');
        $birthday = $request->input('edit_birthday');
        
        $successFlag = NewStudent::updateOrCreate([
            'exam_code' => $exam_code,
        ],[
            'name' => $name,
            'sex' => $sex,
            'mobile' => $mobile,
            'address' => $address,
            'card_type' => $card_type,
            'card_number' => $card_number,
            'birthday' => $birthday,
        ]);
        
        if($successFlag){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 删除班级基本信息
     *
     * @param NewStudent $request
     * @return array
     */
    public function deleteData(NewStudentRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '考试号[' . $request->input('exam_code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateNewStudent($request);

            // 删除班级信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '考试号[' . $request->input('exam_code') . '],删除成功！';
            }
        }

        return $response;
    }


    /**
     * 批量删除学生基本信息
     *
     * @param Request $request
     * @return array
     */
    public function deleteBatchData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '迎新换届批量删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '班级批量删除成功！';
            }
        }

        return $response;
    }


    /***
     * 处理添加
     * @param Request $request
     * @return mixed
     */
    public function handleAdd(Request $request) {
        $arrival_code =$this->getArrivalCodes();
        // 拼装新增数据数组
        $insertData = [
            'arrival_code' => $arrival_code,
            'enrollment_numbering' => $request->input('enrollment_numbering'),
            'exam_code' => $request->input('exam_code'),
            'name' => $request->input('name'),
            'sex' => $request->input('sex'),
            'avatar' => $request->input('avatar'),
            'mobile' => isset($request['mobile']) ? $request['mobile'] : '',
            'address' => isset($request['address']) ? $request['address'] : '',
            'card_type' => isset($request['card_type'])?$request['card_type']:'',
            'card_number' => isset($request['card_number'])?$request['card_number']:'',
            'birthday' => isset($request['birthday'])?$request['birthday']:'',
            'original_type' => isset($request['original_type'])?$request['original_type']:'',
            'enrollment_type' => isset($request['enrollment_type'])?$request['enrollment_type']:'',
            'exam_province' => isset($request['exam_province'])?$request['exam_province']:'',
            'exam_area' => isset($request['exam_area'])?$request['exam_area']:'',
            'graduated_school' => isset($request['graduated_school'])?$request['graduated_school']:'',
            'school_type' => isset($request['school_type'])?$request['school_type']:'',
            'score' => isset($request['score'])?$request['score']:'',
            'political_status' => isset($request['political_status'])?$request['political_status']:'',
            'admission_type' => isset($request['admission_type'])?$request['admission_type']:'',
            'enrollment_category' => isset($request['enrollment_category'])?$request['enrollment_category']:'',
            'enrollment_code' => isset($request['enrollment_code'])?$request['enrollment_code']:'',
            'enrollment_directory' => isset($request['enrollment_directory'])?$request['enrollment_directory']:'',
            'major_directory_code' => isset($request['major_directory_code'])?$request['major_directory_code']:'',
            'academic_category' => isset($request['academic_category'])?$request['academic_category']:'',
            'read_year' => isset($request['read_year'])?$request['read_year']:'',
            'admission_property' => isset($request['admission_property'])?$request['admission_property']:'',
            'school_mode' => isset($request['school_mode'])?$request['school_mode']:'',
            'ethnic' => isset($request['ethnic'])?$request['ethnic']:'',
            'household' => isset($request['household'])?$request['household']:'',
            'support_type' => isset($request['support_type'])?$request['support_type']:'',
            'enrollment_teacher' => isset($request['enrollment_teacher'])?$request['enrollment_teacher']:'',
            'remark' => isset($request['remark'])?$request['remark']:'',
        ];
        Log::info('insert',$insertData);
        $rspObj = NewStudent::updateOrCreate(['exam_code'=>$request->input('exam_code')],$insertData);
        return $rspObj;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的迎新列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getNewStudentList($page = 1, $rows, $arrival_code, $keywords)
    {
        if (!isset($keywords) || empty($keywords)) {
            $data = NewStudent::where('arrival_code', $arrival_code)
                ->orderBy('created_at', 'desc')->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = NewStudent::where('arrival_code', $arrival_code)
                ->where('name', 'like', '%' . $keywords . '%')
                ->orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }


    /***
     * 根据考试号获取学生信息
     * @param $code
     * @return mixed
     *
     */
    private function getNewStudentByCode($code)
    {
        $student = NewStudent::where('exam_code', $code)->first();
        return $student;
    }

    /***
     * 获取学生监护人
     * @param $code
     * @return mixed
     */
    private function getNewStudentCustodianByCode($code)
    {
        $student = Custodians::where('exam_code', $code)->get();
        return $student;
    }

    /**
     * 获取所有招生年份
     *
     * @param $code
     * @return mixed|string
     */
    private function getEnrollmentCodes()
    {
        $years = NewArrival::all()->pluck('code')->toArray();
        return $years;
    }

    /***
     * 获取当前的迎新代码
     * @return array
     */
    private function getArrivalCodes()
    {
        $code = '';
        $years = NewArrival::where('isOn',true)->first();
        if (!empty($years) || isset($years)) {
            $code = $years->code;
        }
        return $code;
    }

    /***
     * 获取学生录取专业
     * @param $code
     */
    public function getAdmissionMajor($code) {
        $major = ResultMajors::where('exam_code',$code)->first();
        if (empty($major)) {
            return '';
        }else {
            return $major->name;
        }
    }
    /***
     * 根据学生代码判断是否住宿
     * @return array
     */
    private function getIsDorm($code)
    {
        $dorm = ResultDorms::where('exam_code',$code)->first();
        if (!empty($dorm) || isset($dorm)) {
            return '是';
        }
        return '否';

    }

    /***
     * 检测是否已报到
     * @param $code
     * @return mixed
     */
    private function getIsRegister($code)
    {

        $is_register = ReceiveStatus::where(['exam_code'=>$code,'type'=>1,'status'=>true])
            ->first();
        if (!empty($is_register) || isset($is_register)) {
            return '是';
        }
        return '否';
    }


    /***
 * 1:报到 2.生活用品发放 3.教材发放 4.校服发放 5.宿舍钥匙发放
 * 获取物品领取状态
 * @param $code
 * @return string
 */
    private function getIsReceive($code, $type)
    {
        $is_register = ReceiveStatus::where(['exam_code'=>$code,'type'=>$type,'status'=>true])
            ->first();
        if (!empty($is_register) || isset($is_register)) {
            return '是';
        }
        return '否';
    }

    /***
     * 检测是否缴费
     * @param $code
     * @return mixed
     */
    private function getIsPay($code)
    {
        $pay = ApplyPays::where(['exam_code'=>$code,'status'=>true])->first();
        if (!empty($pay) || isset($pay)) {
            return '是';
        }
        return '否';
    }


    /***
     * 获取学生分配班级
     * @param $code
     * @return string
     */
    private function getStudentClass($code)
    {
        $class_name = '';
        $stu_class = ResultClasses::where('exam_code', $code)
            ->first();
        if (!empty($stu_class) || isset($stu_class)) {
            $class_name = $stu_class->name;
        }else {
            $class_name = '未分配';
        }
        return $class_name;
    }

    /***
     * 获取学生分配宿舍
     * @param $code
     * @return string
     */
    private function getStudentDorm($code)
    {
        $dorm_name = '';
        $is_dorm = $this->getIsDorm($code);
        if ($is_dorm === '否'){
            $dorm_name = '学生不住宿';
        }else {
            $stu_dorm = ResultDorms::where('exam_code', $code)
                ->first();
            if (!empty($stu_dorm) || isset($stu_dorm)) {
                $dorm_name = $stu_dorm->building.$stu_dorm->floor.$stu_dorm->dorm_code;
            }else{
                $dorm_name = '未分配';
            }
        }
        return $dorm_name;
    }


    ///////////////////////////////////////////////////////////////////
    /// 验证表单请求功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新班级信息验证请求
     *
     * @param Request $request
     */
    private function validateNewStudent(Request $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新班级信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');

        if ($bBatch) { // 批量删除
            foreach ($where as $code) {
                $rspObj = NewStudent::where('exam_code', $code)->delete();
            }
        } else { // 单条删除
            $rspObj = NewStudent::where('exam_code', $where)->delete();
        }

        return $rspObj;
    }


    /**
     * 格式化显示性别信息
     *
     * @param $val
     * @return string
     */
    private function formatSexData($val)
    {
        $strFormat = '无';
        if ($val==1) {
            $strFormat = '男';
        }elseif($val==2){
            $strFormat = '女';
        }elseif(empty($val)){
            $strFormat = '无';
        }
        return $strFormat;
    }
    
    //获取年次
    private function getYearOrder(){
        $Info = NewArrival::get();
        //对字段数据去重处理
        $ResultInfo = array();
        for($i=0;$i<count($Info);$i++){
            if(!in_array($Info[$i]->enrollment_year, $ResultInfo)){
                $ResultInfo[] = $Info[$i]->enrollment_year;
            }
        }
        return $ResultInfo;
    }
    
    //根据年次获取批次
    private function getSerial(){
        $Info = NewArrival::get();
        //对字段数据去重处理
        $ResultInfo = array();
        for($i=0;$i<count($Info);$i++){
            if(!in_array($Info[$i]->enrollment_serial, $ResultInfo)){
                $ResultInfo[] = $Info[$i]->enrollment_serial;
            }
        }
        return $ResultInfo;
    }
}
